#!/usr/bin/env python2.4

from xml.dom.minidom import parse, parseString, Text
from urllib import urlopen
import re

tracking = """
<!--

<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-319751-3";
urchinTracker();
</script>

<script src="utracker.js" type="text/javascript"></script>

-->
"""

def parse_pic(pic):
	url = pic.getAttribute("url")
	height = pic.getAttribute("height")
	width = pic.getAttribute("width")
	return (url, height, width)	

def remove(node):
	node.parentNode.removeChild(node)

print "Content-Type: text/xml\n"

dom = parseString(urlopen("http://www.flickr.com/services/feeds/photos_public.gne?id=46249124%40N00&tags=shoebox&format=rss_200").read())
dom.getElementsByTagName("rss")[0].setAttribute("xmlns:media", "http://search.yahoo.com/mrss/")
dom.getElementsByTagName("title")[0].firstChild.data = "The Shoebox"
dom.getElementsByTagName("link")[0].firstChild.data = "http://razvan.musaloiu.com/shoebox"
dom.getElementsByTagName("description")[0].appendChild(Text())
dom.getElementsByTagName("description")[0].firstChild.data = "RazvanME's photoblog"
dom.getElementsByTagName("generator")[0].firstChild.data = "http://razvan.musaloiu.com/software/shoebox/"
remove(dom.getElementsByTagName("image")[0])
for e in dom.getElementsByTagName("dc:date.Taken"):
	remove(e)
for e in dom.getElementsByTagName("item"):
	e.getElementsByTagName("author")[0].firstChild.data = "razvan@musaloiu.com (RazvanME)"
        title = e.getElementsByTagName("title")[0].childNodes[0].data
        link = e.getElementsByTagName("link")[0].childNodes[0].data
	link = re.sub('http://www.flickr.com/photos/razvanm/(\d*)/',
		   r'http://razvan.musaloiu.com/shoebox/?id=\1', link)
	e.getElementsByTagName("link")[0].childNodes[0].data = link
        pic = e.getElementsByTagName("media:content")[0]

	desc = e.getElementsByTagName("description")
	if desc and desc[0]:
		r = desc[0].childNodes[0].data
		r = r.replace('<p><a href="http://www.flickr.com/people/razvanm/">RazvanME</a> posted a photo:</p>', "")
		r = re.sub('a href="http://www.flickr.com/photos/razvanm/(\d*)/"',
			   r'a href="http://razvan.musaloiu.com/shoebox/?id=\1"', r)
		r = re.sub('img src="(http://static.flickr.com/\d*/\d*_[0-9a-f]*)_m.jpg" width="\d*" height="\d*"',
			   r'img src="\1.jpg"', r)
		r = r.replace("#ddd", "black").strip()
		r += tracking
		desc[0].childNodes[0].data = r
		e.getElementsByTagName("media:text")[0].childNodes[0].data = r 
		#remove(e.getElementsByTagName("media:text")[0])
		
print dom.toxml()
